package com.wondream.myframework.app.common.util;

import com.hazelcast.util.ConcurrentReferenceHashMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 字段工具类
 */
@Slf4j
public class FieldUtils {

    private static final List<Field> EMPTY_FIELD_ARRAY = new ArrayList<>(1);

    /**
     * 软引用
     * 在JVM空间不足的时候，会回收不可达对象和软引用对象
     */
    private static final Map<Class<?>, List<Field>> declaredFieldsCache = new ConcurrentReferenceHashMap<>(64);

    private static final Map<Class<?>, List<Field>> allFieldsCache = new ConcurrentReferenceHashMap<>(64);

    private static final String SET_METHOD_PREFIX = "set";

    private static final String GET_METHOD_PREFIX = "get";

    /**
     * setXXX
     */
    public static String getSetMethodName(String fieldName) {
        return SET_METHOD_PREFIX + StrUtils.firstLetter2UpperCase(fieldName);
    }

    /**
     * getXXX
     */
    public static String getGetMethodName(String fieldName) {
        return GET_METHOD_PREFIX + StrUtils.firstLetter2UpperCase(fieldName);
    }

    /**
     * 获取非空的字段
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object propertyValue = src.getPropertyValue(pd.getName());
            if (propertyValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static <T> void copyMap2Object(Map<Object, Object> map, T object) {
        Field[] declaredFields = object.getClass().getDeclaredFields();
        try {
            for (Field declaredField : declaredFields) {
                if (map.containsKey(declaredField.getName())) {
                    boolean accessible = declaredField.isAccessible();
                    declaredField.setAccessible(true);
                    declaredField.set(object, map.get(declaredField.getName()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[[FieldUtils.copyMap2Object]] set field fail");
        }
    }

    public static boolean isPrimitive(Class<?> type) {
        return type.isPrimitive() ||
                type == String.class ||
                type == Character.class ||
                type == Boolean.class ||
                type == Byte.class ||
                type == Short.class ||
                type == Integer.class ||
                type == Long.class ||
                type == Float.class ||
                type == Double.class;
    }

    public static List<Field> getDeclaredFields(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }
        List<Field> result = allFieldsCache.get(clazz);
        if (result == null) {
            result = new ArrayList<>();
            Field[] declaredFields = clazz.getDeclaredFields();
            result.addAll(Arrays.asList(declaredFields));
            allFieldsCache.put(clazz, result.size() == 0 ? EMPTY_FIELD_ARRAY : result);
        }
        return result;
    }

    public static List<Field> getAllFields(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }
        List<Field> result = allFieldsCache.get(clazz);
        if (result == null) {
            Class targetClass = clazz;
            result = new ArrayList<>();
            do {
                Field[] declaredFields = targetClass.getDeclaredFields();
                result.addAll(Arrays.asList(declaredFields));
                targetClass = targetClass.getSuperclass();
            } while (targetClass != null && targetClass != Object.class);
            allFieldsCache.put(clazz, result.size() == 0 ? EMPTY_FIELD_ARRAY : result);
        }
        return result;
    }

}
